package com.ja.openchat.ui.chat.adapter.viewholder;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.text.Html;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.view.View;
import android.widget.TextView;

import androidx.core.util.Pair;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonObject;
import com.ja.openchat.R;
import com.ja.openchat.ui.OuterShareActivity;
import com.ja.openchat.ui.chat.ConversationFragment;
import com.ja.openchat.ui.chat.PreviewWebViewActivity;
import com.ja.openchat.ui.chat.annotation.EnableContextMenu;
import com.ja.openchat.ui.chat.annotation.MessageContentType;
import com.ja.openchat.ui.chat.annotation.MessageContextMenuItem;
import com.ja.openchat.views.LinkClickListener;
import com.ja.openchat.views.LinkTextViewMovementMethod;
import com.lqr.emoji.MoonUtils;
import com.zy.openchat.Constants;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.message.MessageInfo;
import com.zy.openchat.core.model.message.UiMessage;
import com.zy.openchat.core.model.setting.MessageAttachMenuEvent;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.SpeechRecognizerUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


@MessageContentType(value = TelegramManager.MessageType.MessageType_Text)
@EnableContextMenu
public class TextMessageContentViewHolder extends NormalMessageContentViewHolder {
    @BindView(R.id.contentTextView)
    TextView contentTextView;
    @BindView(R.id.refTextView)
    TextView refTextView;
    @BindView(R.id.textContentView)
    View textContentView;
    @BindView(R.id.translationView)
    View translationView;
    @BindView(R.id.translationTextView)
    TextView translationTextView;
    @BindView(R.id.translationLable)
    View translationLable;
    @BindView(R.id.translationProgress)
    View translationProgress;

    public TextMessageContentViewHolder(ConversationFragment fragment, RecyclerView.Adapter adapter, View itemView) {
        super(fragment, adapter, itemView);
    }
    public static final int POPU_KEY = R.id.cachePopuViewKey;
    @Override
    public void onBind(UiMessage message) {
        MessageInfo messageInfo = message.message;
        if(messageInfo==null){
            return;
        }
        String content = messageInfo.textTypeContent;
        if(!TextUtils.isEmpty(content)){
            if (content.startsWith("<") && content.endsWith(">")) {
                contentTextView.setText(Html.fromHtml(content));
            } else {

                MoonUtils.identifyFaceExpressionAndAt(fragment.getContext(), contentTextView,content, ImageSpan.ALIGN_BOTTOM,(messageInfo.content==null||messageInfo.content.text==null)?null:messageInfo.content.text.entities);
            }
        }
        contentTextView.setMovementMethod(new LinkTextViewMovementMethod(new LinkClickListener() {
            @Override
            public boolean onLinkClick(String link) {
                try {
                    if(!TextUtils.isEmpty(link)&&link.contains("link=")){
                        String linkContent = link.substring(link.indexOf("link=")+"link=".length());
                        if(!TextUtils.isEmpty(linkContent)){
                            OuterShareActivity.handleOuterInviteLink(fragment.getActivity(), linkContent);
                            return true;
                        }
                    }else if(!TextUtils.isEmpty(link)&&link.contains(":")&&(link.startsWith("@")
                            ||(link.length()>=(Constants.DM_TEXT_LENGTH+1)&&String.format("%s@", Constants.DM_TEXT).equalsIgnoreCase(link.substring(0,Constants.DM_TEXT_LENGTH+1)))
                    )){
                        String[] array = link.split(":");
                        if(array!=null&&array.length>1){
                            fragment.onPortraitClick(UserInfo.getUserInfo(Long.parseLong(array[1])));
                        }
                        return true;
                    }else if(!TextUtils.isEmpty(link)&&link.startsWith(MessageInfo.TmRemindEndText)&&link.contains(":")){
                        String[] array = link.split(":");
                        if(array!=null&&array.length>1){
                            fragment.onRemiitedClick(Long.parseLong(array[1]));
                        }
                        return true;
                    }
                }catch (Exception e){

                }

                PreviewWebViewActivity.loadUrl(fragment.getContext(), "", link);
                return true;
            }

            @Override
            public void onLongLinkClick(String link) {
                if(!TextUtils.isEmpty(link)){
//                    ToastUtils.showShort(link);
                    copyUrl = link;
                    if(textContentView.getParent()!=null&&textContentView.getParent() instanceof View){
                        EventBus.getDefault().post(new MessageAttachMenuEvent());
                    }

                }
            }
        }));

        if(messageInfo.reply_to_message_id>0){
            if(messageInfo.getReplyMessageInfo()!=null){
                initQuoteMessage(messageInfo.getReplyMessageInfo());
            }else{
                TelegramManager.getTelegramManager().getMessage(fragment.getContext(), messageInfo.chat_id, messageInfo.reply_to_message_id, new TgResultBlock<MessageInfo>() {
                    @Override
                    public void onResult(Map<String, Object> request, JsonObject response, MessageInfo obj) {
                        messageInfo.setReplyMessageInfo(obj);
                        initQuoteMessage(obj);
                    }

                    @Override
                    public void onTimeout(Map<String, Object> request) {

                    }
                });
            }
            refTextView.setVisibility(View.VISIBLE);
        }else{
            refTextView.setVisibility(View.GONE);
        }

//        quoteInfo = textMessageContent.getQuoteInfo();
//        if (quoteInfo != null && quoteInfo.getMessageUid() > 0) {
//            refTextView.setVisibility(View.VISIBLE);
//            refTextView.setText(quoteInfo.getUserDisplayName() + ": " + quoteInfo.getMessageDigest());
//        } else {
//            refTextView.setVisibility(View.GONE);
//        }

        if(TextUtils.isEmpty(message.translationText)){
            translationView.setVisibility(View.GONE);
        }else{
            translationTextView.setText(message.translationText);
            translationTextView.setVisibility(View.VISIBLE);
            translationView.setVisibility(View.VISIBLE);
            translationLable.setVisibility(View.VISIBLE);
            translationProgress.setVisibility(View.GONE);
        }

    }

    private void initQuoteMessage(MessageInfo quoteInfo){
        if(quoteInfo==null||quoteInfo.content==null){
            refTextView.setText(fragment.getString(R.string.deleted_message));
            return;
        }
        String content = UserInfo.userDisplayName(quoteInfo.sender_user_id()) + ": " + quoteInfo.toString();
        if (content.startsWith("<") && content.endsWith(">")) {
            refTextView.setText(Html.fromHtml(content));
        } else {
            MoonUtils.identifyFaceExpression(fragment.getContext(), refTextView,content, ImageSpan.ALIGN_BOTTOM);
        }
    }

    @OnClick(R.id.contentTextView)
    public void onClick(View view) {
//        PreviewWebViewActivity.loadHtmlContent(fragment.getActivity(), "消息内容", message.message.textTypeContent);
    }

    @OnClick(R.id.refTextView)
    public void onRefClick(View view) {
        if(message==null||fragment==null){
            return;
        }
        MessageInfo messageInfo = message.message;
        if(messageInfo==null){
            return;
        }
        if(messageInfo.reply_to_message_id>0) {
            fragment.scrollToMessagePositionById(messageInfo.reply_to_message_id,true);
        }
    }

    @MessageContextMenuItem(tag = MessageContextMenuItemTags.TAG_CLIP, confirm = false, priority = 2)
    public void clip(View itemView, UiMessage message) {
        ClipboardManager clipboardManager = (ClipboardManager) fragment.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
        if (clipboardManager == null) {
            return;
        }
        ClipData clipData = ClipData.newPlainText("messageContent", message.message.textTypeContent);
        clipboardManager.setPrimaryClip(clipData);
        ToastUtils.showShort(fragment.getString(R.string.copied_text));
    }

    @MessageContextMenuItem(tag = MessageContextMenuItemTags.TAG_TRANSLATION, confirm = false, priority = 10)
    public void translation(View itemView, UiMessage message) {
        if(!TextUtils.isEmpty(message.translationText)){
            return;
        }
        String content = message.message.textTypeContent;
        if(!TextUtils.isEmpty(content)){
            translationTextView.setVisibility(View.GONE);
            translationLable.setVisibility(View.GONE);
            translationView.setVisibility(View.VISIBLE);
            translationProgress.setVisibility(View.VISIBLE);
            SpeechRecognizerUtil.getInstance()
                    .translation(content)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(String s) {
                            if(translationProgress!=null){
                                translationProgress.setVisibility(View.GONE);
                                translationTextView.setVisibility(View.VISIBLE);
                                translationLable.setVisibility(View.VISIBLE);
                                message.translationText = s;
                                translationTextView.setText(message.translationText);
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            if(translationProgress!=null){
                                translationProgress.setVisibility(View.GONE);
                                translationTextView.setVisibility(View.VISIBLE);
                                translationLable.setVisibility(View.VISIBLE);
                                message.translationText = content;
                                translationTextView.setText(message.translationText);
                            }

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }

    }
    public String copyUrl = null;
    @MessageContextMenuItem(tag = MessageContextMenuItemTags.TAG_CLIP_URL, priority = 8)
    public void onCopyUrl(View itemView, UiMessage message){
        if(!TextUtils.isEmpty(copyUrl)){
            ClipboardManager clipboardManager = (ClipboardManager) fragment.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
            if (clipboardManager == null) {
                return;
            }
            ClipData clipData = ClipData.newPlainText("messageContent", copyUrl);
            clipboardManager.setPrimaryClip(clipData);
            ToastUtils.showShort(fragment.getString(R.string.copied_text));
        }

    }

    @Override
    public Pair<String,Integer> contextMenuTitle(Context context, String tag) {
        if (MessageContextMenuItemTags.TAG_CLIP.equals(tag)) {
            return new Pair<>(context.getString(R.string.copy_text),R.mipmap.menu_copy);
        }
        return super.contextMenuTitle(context, tag);
    }
}
